//
//  PointClassInfoViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/22.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "PointClassInfoViewController.h"
#import "PointClassTableViewCell1.h"
#import "PointClassTableViewCell2.h"
#import "PointClassTableViewCell3.h"
#import "PointClassTableViewCell4.h"
#import "SelectMemberViewController.h"
#import "UserNavigationController.h"

@interface PointClassInfoViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation PointClassInfoViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = BackGroundColor;
    
    self.title = @"详情";
    
    [self createSubView];
}

-(void)createSubView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[PointClassTableViewCell1 class] forCellReuseIdentifier:@"PointClassTableViewCell1"];
    [tableView registerClass:[PointClassTableViewCell2 class] forCellReuseIdentifier:@"PointClassTableViewCell2"];
    [tableView registerClass:[PointClassTableViewCell3 class] forCellReuseIdentifier:@"PointClassTableViewCell3"];
    [tableView registerClass:[PointClassTableViewCell4 class] forCellReuseIdentifier:@"PointClassTableViewCell4"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
    }];
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

#pragma mark 加载数据
-(void)loadData{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    [params setObject:[self.dict objectForKey:@"ID"] forKey:@"CoursePlanItemID"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:GET_CourseOrderListData parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  if (startIndex == 1) {
                      
                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];
                  }
                  else{
                      
                      [self.dataSource addObjectsFromArray:resultArray];
                  }
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}


#pragma mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0 || section == 1) {
        
        return 1;
    }
    else if (section == 2){
        
        return 3;
    }
    else{
        
        return self.dataSource.count;
    }
}

#pragma mark UITableViewDelegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 3) {
        
        UIButton *addBtn = [[UIButton alloc] init];
        addBtn.backgroundColor = CSColor(250, 246, 233);
        [addBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        addBtn.titleLabel.font = MidBigFont;
        [addBtn setTitle:@"添加预约+"];
        [addBtn addTarget:self action:@selector(selectVip)];
        return addBtn;
    }
    
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return CGFLOAT_MIN;
    }
    
    else if (section == 1){
        
        return 10;
    }
    
    else if (section == 2){
        
        return 10;
    }
    
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
     
        PointClassTableViewCell1 *cell1 = [tableView dequeueReusableCellWithIdentifier:@"PointClassTableViewCell1"];
        
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",[self.dict objectForKey:@"Pic"],mid_image];
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [cell1.courseImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
        
        cell1.courseLabel.text = [self.dict objectForKey:@"CourseName"];
        
        [cell1.placeBtn setTitle:[self.dict objectForKey:@"ShopName"]];
        
        int min = [[self.dict objectForKey:@"BeginDateTime"] getDateMinWithOtherDate:[self.dict objectForKey:@"EndDateTime"]];
        
        [cell1.timeBtn setTitle:[NSString stringWithFormat:@"%d分",min]];
        
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell1;
    }
    else if (indexPath.section == 1){
        
        PointClassTableViewCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"PointClassTableViewCell2"];
        
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",[self.dict objectForKey:@"TeacherPic"],mid_image];
        
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [cell2.headImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
        
        cell2.titleLabel.text = [self.dict objectForKey:@"TeacherName"];
        
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell2;
    }
    else if (indexPath.section == 2){
        
        PointClassTableViewCell3 *cell3 = [tableView dequeueReusableCellWithIdentifier:@"PointClassTableViewCell3"];
        
        if (indexPath.row == 0) {
            
            cell3.titleLabel.text = [NSString stringWithFormat:@"%@ - %@",[self.dict objectForKey:@"BeginDateTime"],[self.dict objectForKey:@"EndDateTime"]];
            
            cell3.imageView.image = [UIImage imageNamed:@"courseshare_icon_time"];
            
            cell3.detailLabel.text = @"课程时间";
        }
        else if (indexPath.row == 1){
            
            cell3.titleLabel.text = [NSString stringWithFormat:@"%@",[self.dict objectForKey:@"PlaceName"]];
            cell3.imageView.image = [UIImage imageNamed:@"courseshare_icon_room"];
            cell3.detailLabel.text = @"上课教室";
        }
        else{
            
            cell3.titleLabel.text = [NSString stringWithFormat:@"%@人",[self.dict objectForKey:@"Orders"]];
            cell3.imageView.image = [UIImage imageNamed:@"icon_number"];
            cell3.detailLabel.text = @"人数";
        }
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell3;
    }
    else{
        
        PointClassTableViewCell4 *cell4 = [tableView dequeueReusableCellWithIdentifier:@"PointClassTableViewCell4"];
        
        NSDictionary *dict = self.dataSource[indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",[dict objectForKey:@"Pic"],mid_image];
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [cell4.headImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
        cell4.nickNameLabel.text = [dict objectForKey:@"Name"];
        cell4.detailLabel.text = [[dict objectForKey:@"Memo"] isNull]?@"备注：暂无":[NSString stringWithFormat:@"备注：%@",[dict objectForKey:@"Memo"]];
        //0 是男
        if ([[dict objectForKey:@"Sex"] integerValue] == 0) {
            
            cell4.sexBtn.selected = YES;
        }
        else{
            
            cell4.sexBtn.selected = NO;
        }
        
        [cell4 setBegin:[self.dict objectForKey:@"BeginDateTime"]];
        
        cell4.stateBtn.tag = [[dict objectForKey:@"ID"] integerValue];
        [cell4.stateBtn addTarget:self action:@selector(cancleAppointWithId:)];
        cell4.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell4;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}


#pragma mark 选择会员
-(void)selectVip{
    
    __weak typeof(self)weakSelf = self;
    
    SelectMemberViewController *selectMemberVC = [[SelectMemberViewController alloc] init];
    
    selectMemberVC.memberUrl = Get_MemberList;
    
    selectMemberVC.sendUserBlock = ^(UserAccount *userModel) {
        
        [weakSelf appointClassWithMemberId:userModel.MemberID];
    };
    
    UserNavigationController *naVC = [[UserNavigationController alloc] initWithRootViewController:selectMemberVC];
    
    [self presentViewController:naVC animated:NO completion:nil];
}


#pragma mark 约课
-(void)appointClassWithMemberId:(NSString *)memberId{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    [params setObject:[NSString stringWithFormat:@"%@",[self.dict objectForKey:@"ID"]] forKey:@"CoursePlanItemID"];
    
    [params setObject:memberId forKey:@"MemberID"];
    
    [HTTPTool POSTRaw:Post_CourseOrderOperate parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  [self loadStartData];
              }
          }
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark 取消预约
-(void)cancleAppointWithId:(UIButton *)btn{
    
    NSString *orderId = [NSString stringWithFormat:@"%ld",btn.tag];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    NSString *cancleUrl = [NSString stringWithFormat:@"%@/%@",Post_CancleCourseOrder,orderId];
    
    [HTTPTool POSTRaw:cancleUrl parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [self loadStartData];
                  }
              }
              failure:^(NSError *error){
                  
                  [self.tableView.mj_header endRefreshing];
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
}


#pragma mark 设置数据源
-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

@end
